package gui.table;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;

import javax.swing.JTable;
import javax.swing.table.TableColumnModel;

/**
 * @author Ann Raboschuk
 * 
 */
public class ColumnListener extends MouseAdapter
{
   private JTable table;
   protected int sortColumn = 0;
   protected boolean isAscendingMode = true;

   public ColumnListener(JTable table)
   {
      this.table = table;
   }

   public void mouseClicked(MouseEvent event)
   {
      if (event.getClickCount() == 2)
      {
         TableColumnModel colModel = table.getColumnModel();
         int columnModelIndex = colModel.getColumnIndexAtX(event.getX());
         int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();

         if (modelIndex < 0)
            return;
         if (sortColumn == modelIndex)
            isAscendingMode = !isAscendingMode;
         else
            sortColumn = modelIndex;
         CustomTableModel model = (CustomTableModel) table.getModel();
         Collections.sort(model.getPersons(), model.new ColumnSorter(
               modelIndex, isAscendingMode));
         table.repaint();
      }
   }
}
